package handler

import (
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"yk/api/request"
	"yk/global"
	"yk/internal/dao"
	"yk/internal/model"
	"yk/pkg"
)

func AddBarrage(c *gin.Context) {
	var req request.AddBarrage
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "参数验证",
			"data": err.Error(),
		})
		return
	}

	var video model.Video
	dao.GetOneById(req.UserId, &video)
	if video.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "视频不存在",
			"data": nil,
		})
		return
	}

	if !UpdateBarrage(video, req, c.GetUint("userId")) {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "发送弹幕失败",
			"data": nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "发送弹幕成功",
		"data": true,
	})
}

func UpdateBarrage(video model.Video, req request.AddBarrage, userId uint) bool {
	tx := global.DB.Begin()

	if !pkg.TextCensor(req.Content) {
		log.Println("内容违规")
		return false
	}

	if err := tx.Create(&model.Barrage{
		UserId:  userId,
		VideoId: req.VideoId,
		Content: req.Content,
	}).Error; err != nil {
		tx.Rollback()
		return false
	}

	if err := tx.Updates(&model.Video{
		Id:         video.Id,
		ContentNum: video.ContentNum + 1,
	}).Error; err != nil {
		tx.Rollback()
		return false
	}

	tx.Commit()
	return true

}

func ListBarrage(c *gin.Context) {
	var list []model.Barrage

	dao.ListBarrage(&list)

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": list,
	})
}
